using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Application.Services;

namespace UniversalAdmin.WebApi.Controllers;

[ApiController]
[Route("api/v1/[controller]")]
public class ChatHistoryController : ControllerBase
{
    private readonly IChatHistoryService _chatHistoryService;

    public ChatHistoryController(IChatHistoryService chatHistoryService)
    {
        _chatHistoryService = chatHistoryService;
    }

    [HttpPost]
    [Authorize]
    public async Task<IActionResult> CreateChatHistory([FromBody] CreateChatHistoryDto dto)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        // 设置对话历史的用户ID
        dto.UserId = Guid.Parse(userId);

        try
        {
            var chatHistory = await _chatHistoryService.CreateChatHistoryAsync(dto);
            return CreatedAtAction(nameof(GetChatHistoryById), new { id = chatHistory.Id }, chatHistory);
        }
        catch (ArgumentException ex)
        {
            return BadRequest(new { message = ex.Message });
        }
    }

    [HttpGet("{id}")]
    [Authorize]
    public async Task<IActionResult> GetChatHistoryById(Guid id)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var chatHistory = await _chatHistoryService.GetChatHistoryByIdAsync(id);
        if (chatHistory == null)
        {
            return NotFound();
        }

        // 检查是否为所有者或管理员
        if (chatHistory.UserId != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        return Ok(chatHistory);
    }

    [HttpGet("user")]
    [Authorize]
    public async Task<IActionResult> GetChatHistoriesByUser([FromQuery] int pageIndex = 1, [FromQuery] int pageSize = 10)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var pagedResult = await _chatHistoryService.GetChatHistoriesByUserAsync(Guid.Parse(userId), pageIndex, pageSize);
        return Ok(pagedResult);
    }

    [HttpGet("session/{sessionId}")]
    [Authorize]
    public async Task<IActionResult> GetChatHistoriesBySessionId(string sessionId)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var chatHistories = await _chatHistoryService.GetChatHistoriesBySessionIdAsync(sessionId);
        if (chatHistories == null || !chatHistories.Any())
        {
            return NotFound();
        }

        // 检查是否为所有者或管理员
        if (chatHistories.First().UserId != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        return Ok(chatHistories);
    }

    [HttpGet("recent")]
    [Authorize]
    public async Task<IActionResult> GetRecentChatHistories([FromQuery] int count = 5)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var chatHistories = await _chatHistoryService.GetRecentChatHistoriesAsync(Guid.Parse(userId), count);
        return Ok(chatHistories);
    }

    [HttpGet("search")]
    [Authorize]
    public async Task<IActionResult> SearchChatHistories([FromQuery] string keyword)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        if (string.IsNullOrEmpty(keyword))
        {
            return BadRequest(new { message = "搜索关键词不能为空" });
        }

        var chatHistories = await _chatHistoryService.SearchChatHistoriesAsync(Guid.Parse(userId), keyword);
        return Ok(chatHistories);
    }

    [HttpDelete("{id}")]
    [Authorize]
    public async Task<IActionResult> DeleteChatHistory(Guid id)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var chatHistory = await _chatHistoryService.GetChatHistoryByIdAsync(id);
        if (chatHistory == null)
        {
            return NotFound();
        }

        // 检查是否为所有者或管理员
        if (chatHistory.UserId != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        var result = await _chatHistoryService.DeleteChatHistoryAsync(id);
        if (!result)
        {
            return NotFound();
        }
        return NoContent();
    }

    [HttpDelete("session/{sessionId}")]
    [Authorize]
    public async Task<IActionResult> DeleteChatHistoriesBySessionId(string sessionId)
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var chatHistories = await _chatHistoryService.GetChatHistoriesBySessionIdAsync(sessionId);
        if (chatHistories == null || !chatHistories.Any())
        {
            return NotFound();
        }

        // 检查是否为所有者或管理员
        if (chatHistories.First().UserId != Guid.Parse(userId) && !User.IsInRole("Admin") && !User.IsInRole("SuperAdmin"))
        {
            return Forbid();
        }

        var result = await _chatHistoryService.DeleteChatHistoriesBySessionIdAsync(sessionId);
        if (!result)
        {
            return NotFound();
        }
        return NoContent();
    }

    [HttpGet("session-count")]
    [Authorize]
    public async Task<IActionResult> GetSessionCount()
    {
        var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
        if (string.IsNullOrEmpty(userId))
        {
            return Unauthorized();
        }

        var count = await _chatHistoryService.GetSessionCountAsync(Guid.Parse(userId));
        return Ok(new { count });
    }
}